package com.jrx.anytxn.param.transaction.job.billCompare.step;

import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlBillTransCompareDetail;
import com.jrx.anytxn.param.entity.TlThirdBillDetail;
import com.jrx.anytxn.param.mapper.ext.ExtTlThirdBillDetailMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.transaction.config.BillCompareConfig;
import com.jrx.anytxn.param.transaction.job.billCompare.bean.ThirdBillDetilReadBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlDisbursementLog;
import com.jrx.anytxn.transaction.entity.TlTransactionInfo;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlTransactionInfoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class BillDetailForFKProcessor implements ItemProcessor<TlDisbursementLog, ThirdBillDetilReadBean> {

    private static final Logger logger = LoggerFactory.getLogger(BillDetailForFKProcessor.class);


    @Autowired
    private ISegmentService iSegmentService;
    @Autowired
    private BillCompareConfig billCompareConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Resource
    private ExtTlThirdBillDetailMapper extTlBillThirdDetailMapper;
    @Resource
    private ExtTlTransactionInfoMapper extTlTransactionInfoMapper;

    @Override
    public ThirdBillDetilReadBean process(TlDisbursementLog item) throws Exception {
        // 非T24的对账不执行
        if (!"T24".equalsIgnoreCase(billCompareConfig.getThirdChannel())) {
            return null;
        }
        // 失败的放款不校验
        if (TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_F.equalsIgnoreCase(item.getSumStatus())) {
            return null;
        }
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.XIB_ORG_NUMBER);
        // 设置指定对账日期
        Date today = billCompareConfig.getToday();
        if (Objects.nonNull(today)) {
            org.setToday(today);
        }
        today = org.getToday();
        List<TlThirdBillDetail> tlBillTransDetailList = new ArrayList<>();
        List<TlBillTransCompareDetail> tlBillTransCompareDetailList = new ArrayList<>();
        String refNo = item.getRefNo();

        String tenantId = item.getTenantId();
        String organizationId = item.getOrganizationId();
        TlThirdBillDetail detail = extTlBillThirdDetailMapper.selectByThirdSeqAndType(refNo, tenantId, billCompareConfig.getThirdChannel(), "I" );
        // 根据payId查询溢缴款金额
        BigDecimal totalAmt = item.getAmount();

        boolean todayLoan = today.compareTo(item.getBusinessDate()) == 0;
        // 1.是当日的数据
        if (todayLoan) {
            // 构建一个虚假的交易对象
            if (Objects.isNull(detail) || Objects.isNull(detail.getId())) {
                detail = new TlThirdBillDetail();
                detail.setTransStatus("6");
                detail.setBusinessDate(today);
                detail.setTransactionAmount(BigDecimal.ZERO);
            }
            String transStatus = detail.getTransStatus();
            Date businessDate = detail.getBusinessDate();
            if (Objects.nonNull(detail.getId())) {
                detail.setTransactionAmount(totalAmt);
            }
            BigDecimal transactionAmount = detail.getTransactionAmount();
            boolean transCompareStatus = (!"000000000".equals(transStatus) && !"0".equals(transStatus));
            if (Objects.nonNull(detail.getId())) {
                if (transCompareStatus || totalAmt.compareTo(transactionAmount) != 0) {
                    buildTlBillTransCompareDetail(item, tlBillTransCompareDetailList, refNo, tenantId, organizationId, transStatus, businessDate, transactionAmount);
                }
                TlThirdBillDetail updata = new TlThirdBillDetail();
                updata.setId(detail.getId());
                updata.setCompareFlag(Constant.COMPARE_FLAG_1);
                updata.setDataFrom(billCompareConfig.getDataFrom());
                tlBillTransDetailList.add(updata);
            } else {
                buildTlBillTransCompareDetail(item, tlBillTransCompareDetailList, refNo, tenantId, organizationId, transStatus, businessDate, transactionAmount);
            }
        } else if (Objects.nonNull(detail)) {
            // 2.非当日的数据且三方明细不为空
            String transStatus = detail.getTransStatus();
            Date businessDate = detail.getBusinessDate();
            if (Objects.nonNull(detail.getId())) {
                detail.setTransactionAmount(totalAmt);
            }
            BigDecimal transactionAmount = detail.getTransactionAmount();
            boolean transCompareStatus = (!"000000000".equals(transStatus) && !"0".equals(transStatus));
            if (transCompareStatus || totalAmt.compareTo(transactionAmount) != 0) {
                buildTlBillTransCompareDetail(item, tlBillTransCompareDetailList, refNo, tenantId, organizationId, transStatus, businessDate, transactionAmount);
            }
            TlThirdBillDetail updata = new TlThirdBillDetail();
            updata.setId(detail.getId());
            updata.setCompareFlag(Constant.COMPARE_FLAG_1);
            updata.setDataFrom(billCompareConfig.getDataFrom());
            tlBillTransDetailList.add(updata);
        } else {
            logger.warn("该用户{}的还款payId{}非当日{}，且没有三方明细", item.getCustomerId(), refNo, today);
        }

        ThirdBillDetilReadBean billDetailReadBean = new ThirdBillDetilReadBean();
        billDetailReadBean.setTlBillTransDetilList(tlBillTransDetailList);
        billDetailReadBean.setTlBillTransCompareDetailList(tlBillTransCompareDetailList);
        return billDetailReadBean;
    }

    /**
     * 构建对账结果明细表对象
     * @param item
     * @param tlBillTransCompareDetailList
     * @param payId
     * @param tenantId
     * @param organizationId
     * @param transStatus
     * @param businessDate
     * @param transactionAmount
     * @throws SegmentException
     */
    public void buildTlBillTransCompareDetail(TlDisbursementLog item, List<TlBillTransCompareDetail> tlBillTransCompareDetailList, String payId, String tenantId, String organizationId, String transStatus, Date businessDate
            , BigDecimal transactionAmount) throws SegmentException {
        TlBillTransCompareDetail tlBillTransCompareDetail = new TlBillTransCompareDetail();
        tlBillTransCompareDetail.setId(iSegmentService.getId("TlBillTransCompareDetail"));
        tlBillTransCompareDetail.setTenantId(tenantId);
        tlBillTransCompareDetail.setOrganizationId(organizationId);
        tlBillTransCompareDetail.setBillType(Constant.TRANSACTION_TYPE_XF);
        tlBillTransCompareDetail.setCompareStatus(Constant.COMPARE_FLAG_0);
        tlBillTransCompareDetail.setCompareDesc("放款金额或状态不平");
        tlBillTransCompareDetail.setCustomerId(item.getCustomerId());
        tlBillTransCompareDetail.setSeqNo(StringUtils.isBlank(payId) ? "" : payId);
        // 1.根据之前的还款流水找出退款的原借据编号
        TlTransactionInfo tlTransactionInfo = extTlTransactionInfoMapper.selectBySeqNo(payId, item.getCustomerId(), tenantId);
        String loanId = "";
        if (Objects.nonNull(tlTransactionInfo)) {
            loanId = tlTransactionInfo.getLoanId();
        }
        tlBillTransCompareDetail.setLoanNumber(loanId);
        tlBillTransCompareDetail.setDetailAmount(transactionAmount);
        tlBillTransCompareDetail.setTxnPostingAmnt(item.getAmount());
        tlBillTransCompareDetail.setBillTransStatus(transStatus);
        tlBillTransCompareDetail.setTxnTransStatus(item.getSumStatus());
        tlBillTransCompareDetail.setDataFrom(billCompareConfig.getDataFrom());
        tlBillTransCompareDetail.setBusinessDate(businessDate);
        tlBillTransCompareDetail.setThirdChannel("T24");
        tlBillTransCompareDetailList.add(tlBillTransCompareDetail);
    }
}
